#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <sys/select.h>

int main(int argc, const char *argv[])
{
  // 创建套接字
  int fd = socket(AF_INET, SOCK_DGRAM, 0);
  if(fd == -1)
  {
    perror("创建套接字失败\n");
    exit(1);
  }
  struct sockaddr_in serv;
  memset(&serv, 0, sizeof(serv));
  serv.sin_addr.s_addr = htonl(INADDR_ANY);
  serv.sin_family = AF_INET;
  serv.sin_port = htons(8888);
  socklen_t len = sizeof(serv);
  int ret = bind(fd, (const struct sockaddr*)&serv, len);
  if (ret == -1)
  {
      perror("bind error");
      exit(1);
  }

  struct sockaddr_in client;
  socklen_t client_len = sizeof(client);
  while(1)
  {
    char buf[1024] = {0};
    int recvlen = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&client, &client_len);
    if(recvlen == -1)
    {
      perror("recvfrom error");
      exit(1);
    }
    printf("recv buf: %s\n", buf);
    sendto(fd, buf, strlen(buf)+1, 0, (const struct sockaddr*)&client, len);
  }
  close(fd);
  return 0;
}
